<template>
  <el-dialog
    width="500px"
    title="员工导入"
    :visible="showExcelDialog"
    @close="$emit('update:showExcelDialog',false)"
  >
    <el-row type="flex" justify="center">
      <div class="unload-excel">
        <input
          ref="excel-upload-input"
          type="file"
          class="excel-unload-input"
          accept=".xlsx,.xls"
          @change="uploadChange"
        >
        <div class="drop">
          <i class="el-icon-upload" />
          <el-button type="text" @click="getTemplate">下载导入模版</el-button>
          <span>
            将文件拖到此处或
            <el-button type="text" @click="handleUpLoad">点击上传
            </el-button></span>
        </div>
      </div>
    </el-row>
    <el-row type="flex" justify="end">
      <el-button
        size="mini"
        type="primary"
        @click="$emit('update:showExcelDialog',false)"
      >取消</el-button>
    </el-row>

  </el-dialog>
</template>

<script>
import { getTemplate, handleUpLoad } from '@/api/employee'
import FileSaver from 'file-saver'

export default {
  props: {
    showExcelDialog: {
      type: Boolean,
      default: false
    }
  },
  methods: {
    async getTemplate() {
      const data = await getTemplate()
      FileSaver.saveAs(data, '员工导入模版.xlsx')
    },
    handleUpLoad() {
      this.$refs['excel-upload-input'].click()
    },
    async uploadChange(e) {
      const files = e.target.files
      if (files.length > 0) {
        const data = new FormData()
        data.append('file', files[0])
        // append为formdata对象添加文本、文件、bolb等
        // 属性为后端约定好的
        try {
          await handleUpLoad(data)
          this.$emit('uploadSuccess')
          this.$emit('update:showExcelDialog', false)
        } catch (error) {
          //   this.$refs['excel-upload-input'].value = ''
        } finally {
          this.$refs['excel-upload-input'].value = ''
          // 将输入框的值清空
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.unload-excel{
    display: flex;
    justify-content: center;
    align-content: center;
    width: 360px;
    height: 180px;
    margin: 20px;
    .excel-unload-input{
        display: none;
        z-index: -9999;
    }
    .btn-unload,
    .drop{
        display: flex;
        flex-direction: column;
        justify-content: center;
        line-height: 160px;
        border: 1px dashed #dcdfe6;
        width: 100%;
        height: 100%;
        text-align: center;
        border-radius: 8px;
    }
    .drop{
        line-height: 40px;
        color: #bbb;
        i{
            font-size: 60px;
            display: block;
            color: #c0c4cc;
        }
    }

}

</style>
